/******************************************************
 *                                                     
 *              Score System               
 *                                                     
 *******************************************************/

/**
 * UpdateServlet.java
 *
 * 网页的响应Servlet
 *
 * @author sundy
 * @version 0.0.1
 * lastModified 2011-01-01
 */

package com.sundy.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sundy.core.Context;
import com.sundy.tools.WebUtility;

public class UpdateServlet extends AbstractServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5243422420617387920L;
	private static Logger logger = Logger.getLogger(UpdateServlet.class);

	public UpdateServlet() {
	}

	protected void doGet(Context context, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(context, request, response);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(Context context, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action.equals("keepalive")) {
			// do nothing here
			return;
		} else if (action.equals("update")) {
			String subjectId = request.getParameter("subject");
			Enumeration<String> e = request.getParameterNames();
			logger.info(String.format("%s modify", context.getCurrentUser()
					.getName()));
			while (e.hasMoreElements()) {
				String name = e.nextElement();
				if (name.startsWith("student")) {
					try {
						String value = request.getParameter(name);
						name = name.substring(7);
						if (value == null || value.trim().equals(""))
							continue;
						WebUtility.writeScore(Integer.valueOf(name), Integer
								.valueOf(subjectId), Integer.valueOf(value));
					} catch (NumberFormatException ex) {
						logger.error("NumberFormatException", ex);
					}
				}
			}
			String finished = request.getParameter("finished");
			logger.info(String.format("%s modified", context.getCurrentUser()
					.getName()));
			String desc = request.getParameter("desc");
			if (finished.equals("1")) {
				WebUtility.setFinished(Integer.valueOf(subjectId), Integer
						.valueOf(desc), 1);
				response.sendRedirect(request.getContextPath());
			} else
				response.sendError(204);
		} else if (action.equals("resetsubject")) {
			String subjectId = request.getParameter("subject");
			String desc = request.getParameter("desc");
			WebUtility.setFinished(Integer.valueOf(subjectId), Integer
					.valueOf(desc), 0);
			response.sendRedirect(request.getContextPath());
		}
	}
}
